package net.zoneland.knowledge.service.impl;

import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import net.zoneland.knowledge.model.ScheduledTask;
import net.zoneland.knowledge.service.NotifyService;
import net.zoneland.knowledge.service.ScheduledTaskJobService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ScheduledTaskNotifyImpl implements ScheduledTaskJobService {

    /**
     * logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledTaskNotifyImpl.class);

    /**
     * 通知服务接口.
     */
    @Resource
    private NotifyService notifyService;

    /**
     * 发送邮件.
     *
     * @param scheduledTask 定时任务
     */
    @SchedulerLock(name = "knowledgeBaseUpdateNotifyEmails", lockAtMostFor = "10M", lockAtLeastFor = "5M")
    public void sendEmails(final ScheduledTask scheduledTask) {

        final String title = scheduledTask.getTaskName();
        final String content = scheduledTask.getNotificationContent();
        final String[] receivers = getReceivers(scheduledTask);
        LOGGER.info("定时任务: {}，表达式：{}，发邮件标题：{}， 收件人：{}", scheduledTask.getTaskName(), scheduledTask.getCron(), title, receivers);

        notifyService.notifyByEmail(receivers, title, content);
    }

    /**
     * 发送短信.
     *
     * @param scheduledTask 定时任务
     */
    @SchedulerLock(name = "knowledgeBaseUpdateNotifyMessages", lockAtMostFor = "10M", lockAtLeastFor = "5M")
    public void sendMessages(final ScheduledTask scheduledTask) {

        final String content = scheduledTask.getNotificationContent();
        final String[] receivers = getReceivers(scheduledTask);
        LOGGER.info("定时任务: {}，表达式：{}，发短信内容：{}， 收件人：{}", scheduledTask.getTaskName(), scheduledTask.getCron(), content, receivers);

        notifyService.notifyBySms(receivers, content);
    }

    /**
     * 获取收件人.
     *
     * @param scheduledTask 定时任务
     * @return 收件人
     */
    private String[] getReceivers(final ScheduledTask scheduledTask) {

        final String receiver = scheduledTask.getStaffing();
        final String createBy = scheduledTask.getCreateBy();

        return StringUtils.isNotBlank(receiver) ? StringUtils.split(receiver, ",") : new String[]{createBy};

    }

}
